package top.yokey.learn1.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import top.yokey.learn1.MyApp;
import top.yokey.learn1.MyBroadcastReceiver;
import top.yokey.learn1.MyBroadcastReceiver1;
import top.yokey.learn1.MyService;
import top.yokey.learn1.R;
import top.yokey.learn1.view.FixedViewPager;
import top.yokey.learn1.view.FragmentAdapter;
import top.yokey.learn1.xiti.LoginActivity;

public class MainActivity extends AppCompatActivity {

    private FixedViewPager mainViewPager = null;
    private AppCompatTextView[] mainTextView = new AppCompatTextView[5];
    private Drawable[] normalDrawable = new Drawable[5];
    private Drawable[] pressDrawable = new Drawable[5];
    private Intent intent;

    private MyBroadcastReceiver1 myBroadcastReceiver1 = new MyBroadcastReceiver1();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
        intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
        registerReceiver(myBroadcastReceiver1, intentFilter);

        intent = new Intent(this, MyService.class);


        mainViewPager = findViewById(R.id.mainViewPager);
        mainTextView[0] = findViewById(R.id.homeTextView);
        mainTextView[1] = findViewById(R.id.shopTextView);
        mainTextView[2] = findViewById(R.id.addTextView);
        mainTextView[3] = findViewById(R.id.messageTextView);
        mainTextView[4] = findViewById(R.id.mineTextView);

        normalDrawable[0] = getDrawable(R.drawable.ic_navigation_home);
        normalDrawable[1] = getDrawable(R.drawable.ic_navigation_shop);
        normalDrawable[2] = getDrawable(R.drawable.ic_navigation_add);
        normalDrawable[3] = getDrawable(R.drawable.ic_navigation_message);
        normalDrawable[4] = getDrawable(R.drawable.ic_navigation_mine);
        pressDrawable[0] = getDrawable(R.drawable.ic_navigation_home_press);
        pressDrawable[1] = getDrawable(R.drawable.ic_navigation_shop_press);
        pressDrawable[2] = getDrawable(R.drawable.ic_navigation_add_press);
        pressDrawable[3] = getDrawable(R.drawable.ic_navigation_message_press);
        pressDrawable[4] = getDrawable(R.drawable.ic_navigation_mine_press);

        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new HomeFragment());
        fragmentList.add(new ShopFragment());
        fragmentList.add(new AddFragment());
        fragmentList.add(new MessageFragment());
        fragmentList.add(new MineFragment());
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentList);
        mainViewPager.setAdapter(fragmentAdapter);
        mainViewPager.setScanScroll(true);

        mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateNavigation(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        for (int i = 0; i < mainTextView.length; i++) {
            final int pos = i;
            mainTextView[i].setOnClickListener(view -> {

                Intent intent1 = new Intent();
                intent1.setAction("MyBroad.Custom");
                intent1.putExtra("info", "这是广播带的数据~");
                intent1.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
                sendBroadcast(intent1);

                updateNavigation(pos);
                if (pos == 0) {
                    LiveEventBus.get("test").post("这是从Activity发送来的数据");
                    startService(intent);
                }
                if (pos == 1) {
                    stopService(intent);
                }
            });
        }

        LiveEventBus.get("position", int.class).observe(this, s -> {
            mainViewPager.setCurrentItem(s);
        });

        String key = MyApp.get().getSharedPreferences().getString("key","");
        if(key.isEmpty()){
            Toast.makeText(this,"令牌为空，请重新登陆",Toast.LENGTH_SHORT).show();
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        }

        OkGo.<String>get("https://demo.shopwt.com/api/mobile/index.php?w=member_favorites&t=favorites_list&key="+key+"&curpage=1&page=10").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if (jsonObject.getInt("code") == 400) {
                        jsonObject = jsonObject.getJSONObject("datas");
                        Toast.makeText(MainActivity.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                        MyApp.get().getEditor().putString("key", "").apply();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        finish();
                        return;
                    }
                    jsonObject = jsonObject.getJSONObject("datas");
                    Toast.makeText(MainActivity.this, jsonObject.toString(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void updateNavigation(int position) {

        mainViewPager.setCurrentItem(position);
        for (int i = 0; i < mainTextView.length; i++) {
            mainTextView[i].setCompoundDrawablesWithIntrinsicBounds(null, normalDrawable[i], null, null);
            mainTextView[i].setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.navigation));
        }
        mainTextView[position].setCompoundDrawablesWithIntrinsicBounds(null, pressDrawable[position], null, null);
        mainTextView[position].setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.navigation_press));

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver1);
    }

}
